/*
 * @Author: szx
 * @Date: 2022-03-19 12:27:32
 * @LastEditTime: 2022-03-19 12:37:18
 * @Description:
 * @FilePath: \leetcode\600-699\606\606.js
 */
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {string}
 */
var tree2str = function (root) {
    const res = [];
    const dfs = (root) => {
        if (!root) return;
        res.push(root.val);
        if (!root.left && root.right) {
            res.push('()');
        }
        if (root.left) {
            res.push('(');
            dfs(root.left);
            res.push(')');
        }
        if (root.right) {
            res.push('(');
            dfs(root.right);
            res.push(')');
        }
    };
    dfs(root);
    return res.join('');
};
console.log(tree2str());
